package org.openwebtop.common.security;

import java.util.Collection;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.openwebtop.sunshine.domain.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

public class UserContext implements UserDetails {
	private static final long serialVersionUID = -4227768130799220757L;
	private User user;
	private Collection<GrantedAuthority> authorities;
	private boolean enabled;

	public UserContext(User user, Collection<GrantedAuthority> authorities, boolean enabled) {
		this.user = user;
		this.authorities = authorities;
		this.enabled = enabled;
	}

	@Override
	public String getUsername() {
		return user.getUsername();
	}

	@Override
	public String getPassword() {
		return user.getPassword();
	}

	@Override
	public Collection<GrantedAuthority> getAuthorities() {
		return authorities;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return enabled;
	}

	public User getUser() {
		return user;
	}

	public static UserContext getUserContext() {
		return (UserContext)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}

}
